var pinyin = require("chinese-to-pinyin")
var baiduCommon = require("./baidu")
$(function () {

    let html = "";
    var str;
    // KindEditor.ready(function(K) {
    //     window.editor = K.create('#editor_id', {
    //         allowFlashUpload: false,
    //         themeType: 'simple',
    //         items: ['source', '|', 'fullscreen', 'undo', 'redo', 'print', 'cut', 'copy', 'paste',
    //             'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
    //             'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
    //             'superscript', '|', 'selectall', '-',
    //             'title', 'fontname', 'fontsize', '|', 'textcolor', 'bgcolor', 'bold',
    //             'italic', 'underline', 'strikethrough', 'removeformat', '|',
    //             'hr', 'link', 'unlink',
    //         ],
    //         fontSizeTable: ['14px', '16px', '18px', '24px', '32px'],
    //         filterMode: true,
    //         htmlTags: {
    //             font: ['color', 'size', 'face', '.background-color'],
    //             span: ['style'],
    //             div: ['class', 'align', 'style'],
    //             table: ['class', 'border', 'cellspacing', 'cellpadding', 'width', 'height', 'align', 'style'],
    //             'td,th': ['class', 'align', 'valign', 'width', 'height', 'colspan', 'rowspan', 'bgcolor', 'style'],
    //             a: ['class', 'href', 'target', 'name', 'style'],
    //             embed: ['src', 'width', 'height', 'type', 'loop', 'autostart', 'quality',
    //                 'style', 'align', 'allowscriptaccess', '/'
    //             ],
    //             img: ['src', 'width', 'height', 'border', 'alt', 'title', 'align', 'style', '/'],
    //             hr: ['class', '/'],
    //             br: ['/'],
    //             'p': ['align', 'style'],
    //             'tbody,tr,strong,b,sub,sup,em,u,strike': []
    //         }
    //     });


    // });
    $("#su,.new-inc-rs-table a,#rs_new,body").on("click", function () {
        setTimeout(baiduCommon.baiduText, 500)
    })


    $("#kw").keyup(function () {
        setTimeout(baiduCommon.baiduText, 500)
        setTimeout(baiduCommon.baiduSelectText, 500)
    });
    getTitle()
    //自动显示网页title
    function getTitle() {
        var title = $("title").text();
        var keyWords = $('meta[name="keywords"]').attr("content");
        var description = $('meta[name="description"]').attr("content");
        console.log("title:", title)
        console.log("keyWords:", keyWords)
        console.log("description:", description)
        $("body").append("<div id='bottomHtml' style='position:fixed; bottom:0px; height:100px; width:100%; background:rgba(0,0,0,.8); z-index:9999; color:#fff; font-size:14px'><div id='closed' style='position:absolute; top:10px; right:10px;color:#fff; font-size:14px' >X关闭</div>title:" + title + "<br>keyWords:" + keyWords + "<br>description:" + description + "<br></div>")
    }
    $("#closed").click(function () {
        $("#bottomHtml").hide()
    })
    //拼多多
    if (url.indexOf("pinduoduo.com") > -1) {
        $("body").click(function () {

            html = "";
            let tempArray = [];
            $("ul").find("li div").each(function () {
                if (this.innerText.length < 9) {
                    var str = this.innerText;
                    str = str.replace(/\s+/g, "");
                    tempArray.push(str)
                    //html += $.trim(str) + ","
                }
            });

            tempArray = unique(tempArray);

            tempArray = tempArray.sort(function (a, b) {
                return a.length > b.length;
            })
            tempArray.map(function (item) {
                html += $.trim(item) + ","
            })

            if (html) {
                console.log("%c小于字符长度6", 'color: #43bb88;font-size: 16px;font-weight: bold;')
                console.log(html)
            }


            tempArray = [];
            html = "";
            $("ul").find("li div").each(function () {
                var str = this.innerText;
                str = str.replace(/\s+/g, "");
                //html += $.trim(str) + ","
                tempArray.push(str)
            });
            tempArray = unique(tempArray);
            tempArray = tempArray.sort(function (a, b) {
                return a.length > b.length;
            })
            tempArray.map(function (item) {
                html += $.trim(item) + ","
            })
            console.log("%c全部文本----", 'color: #43bb88;font-size: 16px;font-weight: bold;')
            console.log(html)
        })

    }


    // $("div,p,span,h1,h2,h3,h4,h5").dblclick(function() {

    //     if ($(this).parents("#ssr-content").length) {
    //         str = $(this).parents("._2xiZo1dd2Za0bMpJ-pdB7B").html();
    //     } else {
    //         str = $(this).parent().html();
    //     }

    //     var reg = /style\s*?=\s*?(['"])[\s\S]*?\1/g;
    //     var regClass = /class\s*?=\s*?(['"])[\s\S]*?\1/g;
    //     var regId = /id\s*?=\s*?(['"])[\s\S]*?\1/g;
    //     str = str.replace(/<span (.*?)>|<a (.*?)>|<img (.*?)>|<em (.*?)>|<style (.*?)style>|<iframe (.*?)<\/iframe>|<s(.*?)<\/script>|<div (.*?)>|<div (.*?)>/gi, "");
    //     str = str.replace(reg, '');
    //     str = str.replace(regClass, '');
    //     str = str.replace(regId, '');
    //     str = str.replace(/emsp;|<em>|<\/em>|<i>|<\/i>|<!(.*?)>/g, '');
    //     str = str.replace(/<! (.*?)>/g, '');
    //     str = str.replace(/<a (.*?)a>/g, '');
    //     str = str.replace(/<s(.*?)<\/script>/g, '');
    //     str = str.replace(/<\/script>|<p><\/p>|<\/div>|\n|\t/g, "");

    //     str = str.replace(/[0-9]*?[0-9][.．：；,，、]/gi, "");
    //     str = str.replace(/[零一二三四五六七八九十]*?[零一二三四五六七八九十][.．：；,，、]/g, "");
    //     str = str.replace(/\n[\s| | ]*\r/g, '\n'); //去除多余空行
    //     str = str.replace(/li/gi, "p");



    //     editor.html(str);
    //     $(".robot-content").css({
    //         "position": "fixed",
    //         "top": "50%",
    //         "left": "50%",
    //         "margin": "-300px 0px 0px -400px",

    //     })
    //     event.stopPropagation(); //  阻止事件冒泡 


    // })

    $("body").append(`<div class = 'robot-content' id='robot-content' >

        <textarea class='boxCon' name='content' id='editor_id'></textarea>
        <div class='boxButton'><span id='copyButton'>复制文本</span><span id='copyJson'>生成json</span>
        <span class='hunButton'>混编</span><span class='closeButton'>关闭</span><font>gg手动插入分割</font>
        <div id='boxHtml'></div>
        </div>
        </div>`)

    $("#copyButton").click(function () {
        copyTextHandle()

    })
    $("#copyJson").click(function () {
        editor.sync();
        str = $('#editor_id').val();

        console.log("JSON.stringify(str)----", JSON.stringify(str))
        editor.html(JSON.stringify(str));

    })
    //混编
    $(".hunButton").click(function () {
        editor.sync();
        str = $('#editor_id').val();
        str = str.replace(/emsp;/g, '');
        if (str.indexOf("gg") >= 2) {
            str = str.split("gg");
        } else {
            str = str.split("</p>");
        }

        str.sort(function () {
            return Math.random() - 0.5;
        })

        str = str.filter(function (s) {
            s = s.replace(/\n|\t/g, "");
            return s && s.trim(); //js中的数组去掉空值
        });
        console.log("数组", str)
        str = str.join("&");
        str = str.replace(/&/gi, "");
        editor.html(str);
        $("#boxHtml").html(str);
    })
    $(".closeButton").click(function () {
        $(".robot-content").css({
            "position": "fixed",
            "top": "50000px",
            "left": "50%",
            "marginLeft": "-300px"
        })
    })

    $(".boxCon").click(function () {

        event.stopPropagation(); //  阻止事件冒泡  
    })

})



function copyTextHandle() {
    editor.sync();
    str = $('#editor_id').val();
    console.log("str---", str)
    $("#boxHtml").html(str);
    ButtonClick("boxHtml")


}
//修改默认选择区域
function ButtonClick(id) {
    var div = document.getElementById(id);

    var controlRange;
    if (document.body.createControlRange) {
        controlRange = document.body.createControlRange();
        controlRange.addElement(div);
        controlRange.execCommand('SelectAll');
        console.log("div111", div)
    } else if (window.getSelection) { //标准浏览器
        var sel = window.getSelection();
        sel.selectAllChildren(div)
        console.log("div111", div)
    }
    document.execCommand("Copy"); //执行复制
    debugger
}





$("#content_left >div").each(function (index, item) {
    if (item.className.indexOf("result") > -1) { } else {
        item.style.display = "none"
    }
})

if ($(".result span").text() == "广告") {
    alert("222")
}

//console.log($("#content_left >div").hasClass("result"))
let url = window.location.href;
let html = "";

//天猫
$(".j_More").click(function () {
    html = "";
    $(".row-2").find("li a").each(function () {
        if (this.text.length < 6) {
            html += $.trim(this.text) + ","
        }
    });
    if (html) {
        console.log("%c小于字符长度6", 'color: #43bb88;font-size: 16px;font-weight: bold;')
        console.log(html)
    }



    html = "";
    $(".row-2").find("li a").each(function () {
        html += $.trim(this.text) + ","
    });
    console.log("%c全部文本----", 'color: #43bb88;font-size: 16px;font-weight: bold;')
    console.log(html)
})



$(".s-combobox").click(function () {
    var keyword = [];

    $(".s-mi-cont-key").each(function () {

        keyword.push($.trim(this.innerText))
        //html += $.trim(this.innerText) + ","
    });
    // console.log("%c下拉----", 'color: #43bb88;font-size: 16px;font-weight: bold;')
    //

    $(".relKeyTop").find("li a").each(function () {
        keyword.push($.trim(this.text))

    });

    keyword = [...new Set(keyword)]; //数组去重
    html = "";
    keyword.map(item => {
        if (item.length < 8) {
            html += item + ","
        }
    })
    console.log("%c相关----", 'color: #43bb88;font-size: 16px;font-weight: bold;')
    console.log(html)

    html = "";
    $(".attrValues .av-collapse").eq(0).find("li a").each(function () {
        html += $.trim(this.text) + ","

    });
    console.log("%c品牌----", 'color: #43bb88;font-size: 16px;font-weight: bold;')
    console.log(html)
})


function unique(arr) {
    return Array.from(new Set(arr))
}
$("li").click(function () {

    html = "";
    $(this).parents("ul").find("li a").each(function () {
        if (this.text.length < 6) {
            html += $.trim(this.text) + ","
        }
    });
    if (html) {
        console.log("%c小于字符长度6", 'color: #43bb88;font-size: 16px;font-weight: bold;')
        console.log(html)
    }



    html = "";
    $(this).parents("ul").find("li a").each(function () {
        html += $.trim(this.text) + ","
    });
    console.log("%c全部文本----", 'color: #43bb88;font-size: 16px;font-weight: bold;')
    console.log(html)

    let arrText = [];

    $(this).parents("ul").find("li a").each(function () {

        arrText.push({ 'url': $.trim(this), 'text': $.trim(this.text) })
    });
    console.log("%c带链接数组----", 'color: #43bb88;font-size: 16px;font-weight: bold;')

    console.log(JSON.stringify(arrText))



})


var tianmall = $(".s-mi-list .s-mi-cont-key");
console.log("tianmall", tianmall);
tianmall.each(function () {

    html += $.trim(this.text) + ","

});
console.log("tianmall", html)

var tianmianSearch = $(".relKeyTop li")

tianmianSearch.each(function () {

    html += $.trim(this.text) + ","

});
console.log("tianmianSearch", html)
//获取爱站网站关键词

$(".table,table").click(function () {
    let arrText = [];
    html = "";
    $("tbody tr td.title a").each(function () {
        if (this.text.length < 6) {
            html += $.trim(this.text) + ","
        }

    });
    console.log(html)
    // html = "";
    // $("tbody tr td.title a,ul>li a").each(function () {
    //    // if(this.text.length<8&&this.text.length>5){
    //         html += $.trim(this.text) + ","
    //    // }

    // });
    // console.log(html)  
    html = "";
    $("tbody tr td.title a").each(function () {
        html += $.trim(this.text) + ","
    });
    console.log(html)

    html = "";
    $("tbody tr td.title a").each(function () {
        html += "<li><a href='/search.asp?q=" + $.trim(this.text) + "'>" + $.trim(this.text) + "</a></li>"
    });
    console.log("\n\n<ul class='main-area'>" + html + "</ul>\n\n");


    // $("tbody tr td.title a").each(function (index, item) {

    //     arrText.push({ 'title': $.trim(this.text), 'content': '', 'bigclass': '按摩椅', 'url': getCurrentDate(2) + index })

    // });
    // console.log(JSON.stringify(arrText))
})






//获取站长工具关键词
if (url.indexOf("chinaz.com") > -1) {
    $(".Module-table").click(function () {
        html = "";
        $("#pagedivid .nofoldtxt").text(function (item, element) {

            // html += element + ",";
            html += "<li><a href='/search.asp?q=" + $.trim(element) + "'>" + $.trim(element) + "</a></li>"
        })
        console.log("\n\n<ul class='main-area'>" + html + "</ul>\n\n");
        console.log("\n\n\n");
    })
    setTimeout(function () {
        $("li.nofoldtxt a").each(function () {
            html += $.trim(this.text) + ","
        });
        console.log(html)
    }, 2000)

    $("li").click(function () {
        alert("888666")
        $("li.nofoldtxt a").each(function () {
            console.log(this.text)
        });
    })

}

//获取百度相关搜索推荐

// let arrText = [];
// let baiduConfig={
//     "arrText":"anMoYi",
//     "name":"按摩椅",
//     "pinYin":"anMoYiPin"
// }
// let getArrText=window.localStorage.getItem(baiduConfig.arrText);
// arrText = getArrText?JSON.parse(getArrText):[];

// arrText=arrText.filter(item=>{    
//       return item.indexOf(baiduConfig.name) > -1
// })







var data = new FormData();
data.append('floorId', '20392');
data.append('pageNum', 1);
data.append('pageSize', '60');
data.append('refpid', 'mm_14301670_0_0');
data.append('variableMap', { "fn": "search", "_t": "1618706135083", "q": "坐便器", "toPage": "2", "pageSize": "60" });

var _data_ = { "floorId": "20392", "pageNum": 1, "pageSize": "60", "refpid": "mm_14301670_0_0", "variableMap": { "fn": "search", "_t": "1618706135083", "q": "坐便器", "toPage": "2", "pageSize": "60" } }

function alimama() {
    $.ajax({
        type: "POST",
        contentType: false, // 关关关！必须得 false
        // 这个不关会扔一个默认值 application/x-www-form-urlencoded 过去，后端拿不到数据的！
        // 而且你甚至不能传个字符串 'multipart/form-data'，后端一样拿不到数据！
        processData: false, // 关关关！重点

        url: "https://pub.alimama.com/openapi/json2/1/gateway.unionpub/optimus.material.json?t=1618706182376&_tb_token_=e184fe77db3ee",

        data: data,
        success: function (data) {
            debugger

        }

    })
}
// alimama()
var timer = null
if (url.indexOf("http://www.6cu.com/tool/") > -1) {

    $("#url").val(getParam("url"))
    $('#time').val(15)
    if (!timer) {
        setTimeout(function () { $("#startBtn").trigger("click") }, 200)
    }
    var timer = setInterval(function () {
        window.location.href = window.location.href
        // window.location.reload(); //又弹出提示
        $("#startBtn").trigger("click");

    }, 1000 * 60 * 30)
}



/** 

//情况一:url包含该参数
var url="http:www.baidu.com?a=111&b=222&c=333";
var name="b";
var re=getParam(url,name);

 */

function getParam(name) {
    try {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = url.split('?')[1].match(reg);
        if (r != null) {
            return r[2];
        }
        return ""; //如果此处只写return;则返回的是undefined
    } catch (e) {
        return ""; //如果此处只写return;则返回的是undefined
    }
}